<?php
require_once('webservices.php');

$SESSION_HANDLER_STARTED = false;

$SESSION_HANDLER_CONNECTION = new mysqli($GLOBALS['SERVER_ADDRESS'], $GLOBALS['SERVER_USERNAME'], $GLOBALS['SERVER_PASSWORD'], 'cs414');

function session_handler_main()
{
    exit();
}

function session_handler_start()
{
    global $SESSION_HANDLER_STARTED;
    if (!$SESSION_HANDLER_STARTED)
    {
        $SESSION_HANDLER_STARTED = true;
        session_handler_install();
        session_start();
    }
}

function session_handler_install()
{
    session_set_save_handler('session_handler_open',
                             'session_handler_close',
                             'session_handler_read',
                             'session_handler_write',
                             'session_handler_destroy',
                             'session_handler_gc');
}

// Reference: http://www.tuxradar.com/practicalphp/10/3/7

function session_handler_open($save_path, $name)
{
    return true;
}

function session_handler_close()
{
    return true;
}

function session_handler_read($session_id)
{
    global $SESSION_HANDLER_CONNECTION;
	  $current_time = time();
    $stmt = $SESSION_HANDLER_CONNECTION->prepare('SELECT Data FROM sessions WHERE SessionID = ?;');
    $stmt->bind_param('s', $session_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc())
    {
        $stmt = $SESSION_HANDLER_CONNECTION->prepare('UPDATE sessions SET DateTouched = ? WHERE SessionID = ?;');
        $stmt->bind_param('is', $current_time, $session_id);
        $stmt->execute();
        return $row['Data'];
    }
    $stmt = $SESSION_HANDLER_CONNECTION->prepare('INSERT INTO sessions (DateTouched, SessionID) VALUES (?, ?);');
    $stmt->bind_param('is', $current_time, $session_id);
    $stmt->execute();
    return '';
}

function session_handler_write($session_id, $session_data)
{
    global $SESSION_HANDLER_CONNECTION;
	  $current_time = time();
    $stmt = $SESSION_HANDLER_CONNECTION->prepare('UPDATE sessions SET Data = ?, DateTouched = ? WHERE SessionID = ?;');
    $stmt->bind_param('sis', $session_data, $current_time, $session_id);
    $stmt->execute();
    return true;
}

function session_handler_destroy($session_id)
{
    global $SESSION_HANDLER_CONNECTION;
    $stmt = $SESSION_HANDLER_CONNECTION->prepare('DELETE FROM sessions WHERE SessionID = ?;');
    $stmt->bind_param('s', $session_id);
    $stmt->execute();
    return true;
}

function session_handler_gc($maxlifetime)
{
    global $SESSION_HANDLER_CONNECTION;
	  $current_time = time();
    $stmt = $SESSION_HANDLER_CONNECTION->prepare('DELETE FROM sessions WHERE DateTouched + ? < ?;');
    $stmt->bind_param('ii', $maxlifetime, $current_time);
    $stmt->execute();
    return true;
}

if (!debug_backtrace())
{
    session_handler_main();
}
?>